package com.meterhuang.thread.foobar;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * 信号量控制
 *
 * @author meterhuang
 * @date 2021/09/09 11:05
 */
@Slf4j
public class FooBarSemaphore {

	private int n;

	private Semaphore semaphore1 = new Semaphore(1);
	private Semaphore semaphore2 = new Semaphore(0);

	public FooBarSemaphore(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {
		log.info(Thread.currentThread().getName() + ":foo");
		for (int i = 0; i < n; ++i) {
			semaphore1.acquire();
			printFoo.run();
			semaphore2.release();
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {
		for (int i = 0; i < n; ++i) {
			semaphore2.acquire();
			printBar.run();
			semaphore1.release();
		}
	}

}
